package com.lyon.custom.core;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.lyon.custom.core.parse.NacosDataParserHandler;
import com.lyon.custom.core.store.LyonPropertySourceRepository;

import java.io.IOException;
import java.util.Map;

/**
 * @author LeeYan9
 * @since 2021-11-26
 */
public class LyonPropertySourceBuilder {

    private ConfigService configService;

    public LyonPropertySourceBuilder(ConfigService configService) {
        this.configService = configService;
    }


    public LyonPropertySource build(String dataId, String group, String fileExt) {
        LyonPropertySource lyonPropertySource = loadConfig(dataId, group, fileExt);
        LyonPropertySourceRepository.recordApplicationPropertySource(dataId, group, lyonPropertySource);
        return lyonPropertySource;
    }

    public LyonPropertySource loadConfig(String dataId, String group, String fileExt) {
        // 获取配置
        String[] result = configService.getConfigData(dataId, group, 30000L);
        String content = result[0];
        Map<String, Object> data = MapUtil.empty();
        try {
            // 懒加载解析器, 解析配置
            data = NacosDataParserHandler.getInstance().parseNacosData(content, fileExt);
            return new LyonPropertySource(group, dataId, true, System.currentTimeMillis(), CharSequenceUtil.join(";", group, dataId), data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new LyonPropertySource(group, dataId, true, System.currentTimeMillis(), CharSequenceUtil.join(";", group, dataId), data);
    }

}
